<%--
  Created by IntelliJ IDEA.
  User: Sophie
  Date: 2024/9/10
  Time: 10:30
  To change this template use File | Settings | File Templates.
--%>
<%
    /*获取项目的根路径*/
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    /*basePath就是得到的跟路径类似于：http://localhost:8081/test/*/
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
    <title>${object.name}的空间</title>
    <link rel="shortcut icon" href="<%=basePath%>/img/男女混合.png" type="image/x-icon">
    <link rel="stylesheet" href="<%=basePath%>/css/object.css">
    <link rel="stylesheet" href="<%=basePath%>/css/iconfont/iconfont.css">
    <script src="<%=basePath%>/js/jquery-3.6.3.min.js"></script>
    <script src="<%=basePath%>/js/jquery.validate.min.js"></script>
</head>
<body>
<%@include file="top.jsp" %>
<div class="content">
    <div class="user-item">
        <div class="object-avatar">
            <c:choose>
                <c:when test="${not empty object.avatar}">
                    <img src="${object.avatar}" alt="" class="ava">
                </c:when>
                <c:otherwise>
                    <img src="<%=basePath%>/img/水豚.webp" alt="" class="ava">
                </c:otherwise>
            </c:choose>
        </div>
        <div class="user-name">
            ${object.name}
        </div>
        <div class="people-item">
            <div class="follow">
                <span class="followcount">0</span>
                <span>关注</span>
            </div>

            <div class="fans">
                <span class="fanscount">0</span>
                <span>粉丝</span>
            </div>
            <div class="dynamics">
                <span class="dynamicscount">0</span>
                <span>动态</span>
            </div>
        </div>
        <div class="gender-age">
            <span>${object.gender}</span>
            <span>${object.birthday}</span>
        </div>
        <div class="tag">
            <c:if test="${not empty object.likeType}">
                <c:set var="personalityTypes" value="${object.likeType}"/>
                <c:set var="personalityArray" value="${fn:split(personalityTypes, '-')}"/>
                <c:forEach var="personality" items="${personalityArray}">
                    <span>${personality}</span>
                </c:forEach>
            </c:if>
            <c:if test="${empty object.likeType}">
                <span>快去</span>
                <span>填写</span>
                <span>资料</span>
            </c:if>
        </div>
        <div class="user-detail">
            <div class="hobby">
                <i class="iconfont icon-aihao"></i>
                <span>${object.hobby}</span>
            </div>
            <div class="education">
                <i class="iconfont icon-xueli"></i>
                <span>${object.education}</span>
            </div>
            <div class="address">
                <i class="iconfont icon-zhuzhi"> </i>
                <span>${object.address}</span>
            </div>
            <div class="motto">
                <i class="iconfont icon-gexingqianming"> </i>
                <span>${object.motto}！</span>
            </div>
        </div>
    </div>


    <div class="zone-list">
        <c:if test="${empty objectZone && object.id==user.id}">
            <div style="font-size: 25px;color: #666666">您还未发布过动态，快去发布吧!</div>
        </c:if>
        <c:if test="${empty objectZone && object.id!=user.id}">
            <div style="font-size: 25px;color: #666666;margin-left: 200px;">对方还未发布过动态</div>
        </c:if>
        <c:if test="${not empty objectZone}">
            <c:forEach items="${objectZone}" var="zone">
                <div class="comment-item">
                    <div class="comment-item-top">
                        <div class="item-top-left">
                            <a href=""><img src="${object.avatar}" alt="" class="user-avatar"></a>
                            <div class="item-info">
                                <span class="username">${object.name}</span>
                                <span>
                            <span class="publish-time">
                                    ${zone.publishtime}
                            </span>
                            <span class="signature">${object.motto}</span>
                        </span>

                            </div>
                        </div>
                        <c:if test="${object.id!=user.id}">
                            <div class="item-top-right">
                                <a href="" class="follow" data-id="${zone.userid}">+关注</a>
                            </div>
                        </c:if>
                    </div>
                    <div class="comment-body">
                            ${zone.contenttext}
                        <div class="illustration">
                            <c:if test="${not empty zone.imgs}">
                                <c:set var="imageUrls" value="${zone.imgs}"/>
                                <c:set var="imageUrlArray" value="${fn:split(imageUrls, '+')}"/>
                                <c:forEach var="imageUrl" items="${imageUrlArray}">
                                    <img src="${imageUrl}" alt="Image"/>
                                </c:forEach>
                            </c:if>
                        </div>
                        <div class="comment-item-bottom " data-id="${zone.zoneid}">
                            <div class="icon  collect  is-collected">
                                <i class="iconfont icon-aixin heart"></i>
                                <span class="goodcount">${zone.goodcount}</span>
                            </div>
                            <div class="icon">
                                <i class="iconfont icon-chat"></i>
                                <span class="commentcount">${zone.commentcount}</span>
                            </div>
                            <div class="icon">
                                <i class="iconfont icon-zhuanfa"></i>
                                <span class="transmitcount">${zone.transmitcount}</span>
                            </div>
                        </div>

                        <div class="comment-area" style="display: none" data-id="${zone.zoneid}">
                            <div class="publish-comment">
                                <c:choose>
                                    <c:when test="${not empty user.avatar}">
                                        <img src="${user.avatar}" alt="" class="publish-avatar" width="45px" height="45px">
                                    </c:when>
                                    <c:otherwise>
                                        <img src="<%=basePath%>/img/水豚.webp" alt="" class="publish-avatar" width="45px">
                                    </c:otherwise>
                                </c:choose>
                                <textarea placeholder="发布评论你的评论" class="comment-content"></textarea>
                                <a href="javascript:;" style="display: block;" class="remark" data-id="${zone.zoneid}">评论</a>
                            </div>
                            <div class="comments-list">
                            </div>
                        </div>

                    </div>
                </div>
            </c:forEach>
        </c:if>


    </div>
</div>
<script>
    $(function () {
        //查询对应动态的评论
        $(".comment-area").each(function (){
            let commentarea=$(this);
            let zoneid=commentarea.attr("data-id");
            $.ajax({
                url: "CommentServlet?method=getCommentByZoneId",
                type: "post",
                data: {"zoneid":zoneid},
                success:function (data){
                    // console.log(data.data);
                    if (data==null){
                        commentarea.find(".comments-list").html("<span>暂无评论,快来评论一下吧！</span>")
                    }else {
                        let $commentList=commentarea.find(".comments-list");
                        $commentList.empty();
                        for (let i=0;i<data.length;i++){
                            var comment_item=`
                        <div class="comment">
                            <div class="comment-top">
                                <img src="`+data[i].avatar+`" alt="">
                                <span>
                                    <span class="remarker-name">`+data[i].username+`</span>
                                    <br>
                                    <span class="comment-time">`+data[i].commenttime+`</span>
                                </span>
                            </div>
                            <div class="contenttext">
                                `+data[i].contenttext+`
                            </div>
                        </div>
                            `;
                            $commentList.append(comment_item);
                        }
                    }
                }
            })
        })

        //计算评论数
        $(".commentcount").each(function (){
            let $this=$(this);
            let zoneid=$this.parent().parent().attr("data-id");
            $.ajax({
                url:"CommentServlet?method=countComment",
                type:"post",
                data:{"zoneid":zoneid},
                success:function (data){
                    $this.text(data);
                }
            })
        })

        //动态数量
        var id =${object.id};
        $.ajax({
            url: "ZoneServlet?method=countZone",
            type: "post",
            data: {"id": id},
            success: function (data) {
                if (data > 0) {
                    console.log("data=", data)
                    $(".dynamicscount").text(data);
                }

            }
        })
        //计算粉丝数量
        $.ajax({
            url: "FollowServlet?method=countFans",
            type: "post",
            data: {"id": id},
            success: function (data) {
                if (data > 0) {
                    console.log("data=", data)
                    $(".fanscount").text(data);
                }

            }
        })
        //计算关注的数量
        $.ajax({
            url: "FollowServlet?method=countFollows",
            type: "post",
            data: {"id": id},
            success: function (data) {
                if (data > 0) {
                    console.log("data=", data)
                    $(".followcount").text(data);
                }

            }
        })


        //动态时间
        function updateTimeDisplay() {
            $('.publish-time').each(function () {
                var timeString = $(this).text(); // 获取时间字符串
                var date = new Date(timeString); // 尝试将时间字符串转换为Date对象

                if (!isNaN(date.getTime())) { // 检查Date对象是否有效
                    var timestamp = date.getTime(); // 获取时间戳（毫秒）
                    var now = new Date().getTime(); // 当前时间的时间戳（毫秒）
                    var diff = now - timestamp; // 时间差（毫秒）

                    if (diff < 60000) { // 如果在一分钟内
                        $(this).text('刚刚');
                    } else if (diff < 3600000) { // 如果在一个小时内
                        var minutes = Math.floor(diff / 60000);
                        $(this).text(minutes + '分钟前');
                    } else if (diff < 86400000) { // 如果在一天内
                        var hours = Math.floor(diff / 3600000);
                        $(this).text(hours + '小时前');
                    } else if (diff < 604800000) { // 如果在一个星期内
                        var days = Math.floor(diff / 86400000);
                        $(this).text(days + '天前');
                    } else {
                        // 如果超过一个星期，则显示原始时间字符串（或进行其他处理）
                        $(this).text(timeString);
                    }
                } else {
                    console.error('Invalid date string:', timeString);
                    $(this).text('无效时间');
                }
            });
        }
        updateTimeDisplay();

        //评论时间
        function updateCommentTimeDisplay() {
            $('.comment-time').each(function() {
                var timeString = $(this).text(); // 获取时间字符串
                var date = new Date(timeString); // 尝试将时间字符串转换为Date对象

                if (!isNaN(date.getTime())) { // 检查Date对象是否有效
                    var timestamp = date.getTime(); // 获取时间戳（毫秒）
                    var now = new Date().getTime(); // 当前时间的时间戳（毫秒）
                    var diff = now - timestamp; // 时间差（毫秒）

                    if (diff < 60000) { // 如果在一分钟内
                        $(this).text('刚刚');
                    } else if (diff < 3600000) { // 如果在一个小时内
                        var minutes = Math.floor(diff / 60000);
                        $(this).text(minutes + '分钟前');
                    } else if (diff < 86400000) { // 如果在一天内
                        var hours = Math.floor(diff / 3600000);
                        $(this).text(hours + '小时前');
                    } else if (diff < 604800000) { // 如果在一个星期内
                        var days = Math.floor(diff / 86400000);
                        $(this).text(days + '天前');
                    } else {
                        // 如果超过一个星期，则显示原始时间字符串（或进行其他处理）
                        $(this).text(timeString);
                    }
                } else {
                    $(this).text('无效时间');
                }
            });
        }
        // 首次加载时更新显示
        updateCommentTimeDisplay();
        // 每隔一定时间（比如每分钟）更新一次
        //setInterval(updateCommentTimeDisplay, 60000);

    })
    //生成评论
    $(".remark").click(function () {
        let text = $(this).prev(".comment-content").val();
        let commentarea=$(this).parent().parent(".comment-area");
        let id=$(this).attr("data-id");
        let $this=$(this)
        $.ajax({
            url:"CommentServlet?method=addComment",
            type:"post",
            data:{"id":id,"commenttext":text},
            success:function (data){
                if (data.code==0){
                    //返回刷新评论区
                    $.ajax({
                        url:"CommentServlet?method=getCommentByZoneId",
                        type:"post",
                        data:{"zoneid":id},
                        success:function (data){
                            let count=$this.parent().parent().prev(".comment-item-bottom").find(".commentcount").text();
                            count = parseInt(count, 10) || 0;
                            count++;
                            $this.parent().parent().prev(".comment-item-bottom").find(".commentcount").text(count);
                            if (data==null){
                                commentarea.find(".comments-list").html("<span>暂无评论,快来评论一下吧！</span>")
                            }else {
                                //将文本框内容置为空
                                text='';

                                let $commentList=commentarea.find(".comments-list");
                                $commentList.empty();
                                for (let i=0;i<data.length;i++){
                                    var comment_item=`
                        <div class="comment">
                            <div class="comment-top">
                                <img src="`+data[i].avatar+`" alt="">
                                <span>
                                    <span class="remarker-name">`+data[i].username+`</span>
                                    <br>
                                    <span class="comment-time">`+data[i].commenttime+`</span>
                                </span>
                            </div>
                            <div class="contenttext">
                                `+data[i].contenttext+`
                            </div>
                        </div>
                            `;
                                    $commentList.append(comment_item);
                                }
                            }
                        }
                    })
                }else {
                    alert("fail");
                }
            }
        })
        $(this).prev(".comment-content").val("");
    })

    //点击评论图标展开评论区
    $('.icon-chat').on('click', function () {
        $(this).toggleClass('color-icon');
        var commentArea = $(this).closest('.comment-body').find('.comment-area');
        commentArea.toggle(); // 使用toggle()方法来切换显示状态

    });

    //点击关注关注该对象
    $(".follow").click(function (){
        let $follow=$(this);
        let userid=$follow.attr("data-id");
        $.ajax({
            url:"UserServlet?method=follow",
            type:"post",
            data:{"id":userid},
            success:function (data){
                if(data.code==0){
                    $follow.empty().text("已关注");
                    $(".follow").each(function () {
                        let follow = $(this);
                        var this_id = follow.attr("data-id");
                        if (userid===this_id){
                            follow.empty().text("已关注");
                        }
                    });
                    alert("感谢你的关注!");
                }else {
                    alert("关注失败!");
                }
            }
        })
    })
    //检查是否关注该用户
    $(".follow").each(function () {
        let follow = $(this);
        var id = follow.attr("data-id");
        $.ajax({
            url: "FollowServlet?method=checkFollow",
            type: "post",
            data: {"id": id},
            success: function (data) {
                if (data.code == 0) {
                    follow.empty().text("已关注");
                }
            }
        })
    });

    //点击转发转发该动态
    $(".icon-zhuanfa").click(function (){
        let $this=$(this);
        let zoneid=$this.parent().parent().attr("data-id");
        console.log("transmit->",zoneid);
        $.ajax({
            url:"ZoneServlet?method=countTransmit",
            type:"post",
            data:{"zoneid":zoneid},
            success:function (data){
                $this.next(".transmitcount").text(data);
            }
        })
    })

    //检查是否收藏该动态
    $(".collect").each(function (){
        let $this=$(this);
        let zoneid=$this.closest('[data-id]').attr("data-id");
        $.ajax({
            url:"ZoneServlet?method=checkCollected",
            type:"post",
            data:{"zoneid":zoneid},
            success:function (data){
                if (data!==1){
                    $this.removeClass("is-collected");
                }else{
                    $this.addClass("is-collected");
                    $this.find(".heart").removeClass("icon-aixin");
                }
            }
        })
    })

    //点击爱心图标收藏该动态
    $(".collect").click(function() {
        let $this = $(this);
        let zoneid = $this.closest('[data-id]').attr("data-id"); // 使用 closest 简化父级选择器
        //判断是否有is-collected
        if ($this.hasClass("is-collected")){
            //包含is-collected，进行取消收藏操作
            console.log("cancel");
            $.ajax({
                url:"ZoneServlet?method=cancelZone",
                type:"post",
                data:{"zoneid":zoneid},
                success:function (data){
                    if (data!==0){
                        $this.removeClass("is-collected");
                        $this.find(".heart").addClass("icon-aixin");
                        let goodcount=$this.find(".goodcount").text();
                        goodcount=parseInt(goodcount);
                        goodcount--;
                        if (goodcount===0){
                            $this.find(".goodcount").text("");
                        }else {
                            $this.find(".goodcount").text(goodcount);
                        }
                        alert("已取消收藏!");
                    }
                }
            })
        }else {
            //此时是不包含"is-collected"的，则添加"is-collected"
            console.log("collect")
            $.ajax({
                url:"ZoneServlet?method=collectZone",
                type:"post",
                data:{"zoneid":zoneid},
                success:function (data){
                    if (data!==0){
                        $this.addClass("is-collected");
                        $this.find(".heart").removeClass("icon-aixin");
                        let goodcount=parseInt(data);
                        goodcount++;
                        if (goodcount===0){
                            $this.find(".goodcount").text(null);
                        }else {
                            $this.find(".goodcount").text(goodcount);
                        }
                        alert("收藏成功!")
                    }
                }
            })
        }
    });


</script>
</body>
</html>
